package ld.oauth.blog.config;

import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.IOException;

@Configuration
@RequiredArgsConstructor
public class ResourceTokenConfig {

//    @Autowired
//    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private CustomAccessTokenConvertor customAccessTokenConvertor;


    public static final String STRING_KEY = "public.txt";

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //指定签名的秘钥 现在是对称加密
        //converter.setSigningKey(STRING_KEY);
        //非对称加密 资源服务器采用公钥解密 public.txt
        ClassPathResource resource = new ClassPathResource(STRING_KEY);
        try {
            String publicKey = IOUtils.toString(resource.getInputStream(), "UTF-8");
            converter.setVerifierKey(publicKey);
            converter.setAccessTokenConverter(customAccessTokenConvertor);
        }catch (IOException e){
            e.printStackTrace();
        }
        return converter;
    }


    @Bean
    public TokenStore tokenSTore() {
        //通过redis管理令牌
        //return new RedisTokenStore(redisConnectionFactory);
        //return new JdbcTokenStore(dataSource());
        //jwt方式管理令牌
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
